import os
import json
from typing import Dict, List, Any, Tuple
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from .models import EvaluationAnalysis, ImprovementSuggestion, TrainingRecommendation
from .memory_service import DriverMemoryService

# 初始化千问大模型
llm = ChatOpenAI(
    model="qwen-max",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

class EvaluationAnalysisService:
    """评价分析服务 - 滴滴出行服务评价改进Agent核心服务"""
    
    def __init__(self):
        self.llm = llm
    
    def analyze_evaluation(self, order_rating_id: int) -> Dict[str, Any]:
        """
        分析单个评价
        
        Args:
            order_rating_id: 订单评价ID
        
        Returns:
            分析结果
        """
        from order.models import OrderRating
        
        try:
            # 检查评价是否已存在分析记录
            existing_analysis = EvaluationAnalysis.objects.filter(order_rating_id=order_rating_id).first()
            if existing_analysis:
                return {
                    'success': True,
                    'message': '该评价已存在分析记录',
                    'analysis_id': existing_analysis.id,
                    'existing': True
                }
            
            # 获取评价数据
            try:
                rating = OrderRating.objects.get(id=order_rating_id)
            except OrderRating.DoesNotExist:
                return {
                    'success': False,
                    'error': f'订单评价ID {order_rating_id} 不存在，请先创建评价数据'
                }
            
            # 进行情感分析
            sentiment_result = self._perform_sentiment_analysis(rating.comment)
            
            # 提取关键短语和改进领域
            extraction_result = self._extract_key_phrases_and_improvements(rating.comment, rating.rating)
            
            # 创建分析记录
            analysis = EvaluationAnalysis.objects.create(
                order_rating=rating,
                sentiment_score=sentiment_result['sentiment_score'],
                sentiment_label=sentiment_result['sentiment_label'],
                key_phrases=extraction_result['key_phrases'],
                improvement_areas=extraction_result['improvement_areas']
            )
            
            # 生成改进建议
            suggestions = self._generate_improvement_suggestions(analysis)
            
            # 生成培训建议
            training_recommendations = self._generate_training_recommendations(
                rating.driver_id, 
                analysis, 
                suggestions
            )
            
            # 更新司机记忆
            self._update_driver_memory(rating.driver_id, analysis, suggestions)
            
            return {
                'analysis_id': analysis.id,
                'sentiment_result': sentiment_result,
                'extraction_result': extraction_result,
                'suggestions_count': len(suggestions),
                'training_recommendations_count': len(training_recommendations),
                'success': True
            }
            
        except Exception as e:
            return {'success': False, 'error': str(e)}
    
    def _perform_sentiment_analysis(self, comment: str) -> Dict[str, Any]:
        """
        进行情感分析
        
        Args:
            comment: 评价内容
        
        Returns:
            情感分析结果
        """
        prompt = ChatPromptTemplate.from_template(
            """
            请对以下乘客评价进行情感分析，返回JSON格式结果：
            
            评价内容：{comment}
            
            请分析：
            1. 情感得分：-1到1之间，-1为极度负面，0为中性，1为极度正面
            2. 情感标签：正面/负面/中性
            
            返回格式：
            {{
                "sentiment_score": 0.8,
                "sentiment_label": "正面"
            }}
            """
        )
        
        try:
            chain = prompt | self.llm
            result = chain.invoke({"comment": comment})
            
            # 解析JSON结果
            response_text = result.content
            if isinstance(response_text, str):
                # 尝试提取JSON部分
                start_idx = response_text.find('{')
                end_idx = response_text.rfind('}') + 1
                if start_idx != -1 and end_idx != 0:
                    json_str = response_text[start_idx:end_idx]
                    result_data = json.loads(json_str)
                else:
                    # 如果无法解析，使用默认值
                    result_data = {"sentiment_score": 0.0, "sentiment_label": "中性"}
            else:
                result_data = {"sentiment_score": 0.0, "sentiment_label": "中性"}
            
            return result_data
            
        except Exception as e:
            print(f"情感分析失败: {e}")
            return {"sentiment_score": 0.0, "sentiment_label": "中性"}
    
    def _extract_key_phrases_and_improvements(self, comment: str, rating: int) -> Dict[str, Any]:
        """
        提取关键短语和改进领域
        
        Args:
            comment: 评价内容
            rating: 评分
        
        Returns:
            提取结果
        """
        prompt = ChatPromptTemplate.from_template(
            """
            请分析以下乘客评价，提取关键短语和改进领域：
            
            评价内容：{comment}
            评分：{rating}（1-5分）
            
            请返回JSON格式：
            {{
                "key_phrases": ["短语1", "短语2", "短语3"],
                "improvement_areas": [
                    {{
                        "area": "服务态度",
                        "description": "具体描述",
                        "priority": "高/中/低"
                    }}
                ]
            }}
            
            改进领域分类：
            - 服务态度：礼貌、耐心、沟通等
            - 驾驶技术：安全、平稳、路线等
            - 车辆状况：清洁、舒适、设备等
            - 时间管理：准时、等待时间等
            """
        )
        
        try:
            chain = prompt | self.llm
            result = chain.invoke({"comment": comment, "rating": rating})
            
            response_text = result.content
            if isinstance(response_text, str):
                start_idx = response_text.find('{')
                end_idx = response_text.rfind('}') + 1
                if start_idx != -1 and end_idx != 0:
                    json_str = response_text[start_idx:end_idx]
                    result_data = json.loads(json_str)
                else:
                    result_data = {"key_phrases": [], "improvement_areas": []}
            else:
                result_data = {"key_phrases": [], "improvement_areas": []}
            
            # 确保数据格式正确
            if 'key_phrases' not in result_data:
                result_data['key_phrases'] = []
            if 'improvement_areas' not in result_data:
                result_data['improvement_areas'] = []
            
            # 确保key_phrases是字符串列表
            if isinstance(result_data['key_phrases'], list):
                result_data['key_phrases'] = [str(phrase) for phrase in result_data['key_phrases']]
            else:
                result_data['key_phrases'] = []
            
            # 确保improvement_areas是字典列表
            if isinstance(result_data['improvement_areas'], list):
                for area in result_data['improvement_areas']:
                    if not isinstance(area, dict):
                        result_data['improvement_areas'] = []
                        break
            else:
                result_data['improvement_areas'] = []
            
            return result_data
            
        except Exception as e:
            print(f"关键短语提取失败: {e}")
            return {"key_phrases": [], "improvement_areas": []}
    
    def _generate_improvement_suggestions(self, analysis: EvaluationAnalysis) -> List[ImprovementSuggestion]:
        """
        生成改进建议
        
        Args:
            analysis: 评价分析记录
        
        Returns:
            改进建议列表
        """
        suggestions = []
        
        for area in analysis.improvement_areas:
            suggestion_content = self._generate_suggestion_content(area, analysis.order_rating.comment)
            
            # 确定优先级
            priority_map = {"高": 1, "中": 2, "低": 3}
            priority = priority_map.get(area.get('priority', '中'), 2)
            
            suggestion = ImprovementSuggestion.objects.create(
                analysis=analysis,
                suggestion_type=area.get('area', '其他'),
                suggestion_content=suggestion_content,
                priority=priority
            )
            suggestions.append(suggestion)
        
        return suggestions
    
    def _generate_suggestion_content(self, area: Dict[str, Any], comment: str) -> str:
        """
        生成具体建议内容
        
        Args:
            area: 改进领域
            comment: 原始评价
        
        Returns:
            建议内容
        """
        prompt = ChatPromptTemplate.from_template(
            """
            基于以下信息，为司机生成具体的改进建议：
            
            改进领域：{area}
            乘客评价：{comment}
            
            请生成具体、可操作的改进建议，包括：
            1. 问题分析
            2. 具体改进措施
            3. 预期效果
            
            建议要实用、具体，避免空泛的表述。
            """
        )
        
        try:
            chain = prompt | self.llm
            result = chain.invoke({
                "area": json.dumps(area, ensure_ascii=False),
                "comment": comment
            })
            
            return result.content if hasattr(result, 'content') else "建议司机关注此方面的改进。"
            
        except Exception as e:
            print(f"生成建议内容失败: {e}")
            return f"建议司机改进{area.get('area', '服务')}方面的表现。"
    
    def _generate_training_recommendations(self, driver_id: int, analysis: EvaluationAnalysis, suggestions: List[ImprovementSuggestion]) -> List[TrainingRecommendation]:
        """
        生成培训建议
        
        Args:
            driver_id: 司机ID
            analysis: 评价分析记录
            suggestions: 改进建议列表
        
        Returns:
            培训建议列表
        """
        recommendations = []
        
        # 根据改进建议生成培训建议
        for suggestion in suggestions:
            training_content = self._generate_training_content(suggestion)
            training_materials = self._get_training_materials(suggestion.suggestion_type)
            
            recommendation = TrainingRecommendation.objects.create(
                driver_id=driver_id,
                recommendation_type=suggestion.suggestion_type,
                recommendation_content=training_content,
                training_materials=training_materials,
                priority=suggestion.priority
            )
            recommendations.append(recommendation)
        
        return recommendations
    
    def _generate_training_content(self, suggestion: ImprovementSuggestion) -> str:
        """
        生成培训内容
        
        Args:
            suggestion: 改进建议
        
        Returns:
            培训内容
        """
        prompt = ChatPromptTemplate.from_template(
            """
            基于以下改进建议，生成相应的培训内容：
            
            建议类型：{suggestion_type}
            建议内容：{suggestion_content}
            
            请生成培训内容，包括：
            1. 培训目标
            2. 培训要点
            3. 实践练习
            4. 评估标准
            
            内容要系统、实用，适合司机学习。
            """
        )
        
        try:
            chain = prompt | self.llm
            result = chain.invoke({
                "suggestion_type": suggestion.suggestion_type,
                "suggestion_content": suggestion.suggestion_content
            })
            
            return result.content if hasattr(result, 'content') else f"关于{suggestion.suggestion_type}的培训内容。"
            
        except Exception as e:
            print(f"生成培训内容失败: {e}")
            return f"关于{suggestion.suggestion_type}的培训内容。"
    
    def _get_training_materials(self, suggestion_type: str) -> Dict[str, Any]:
        """
        获取培训材料
        
        Args:
            suggestion_type: 建议类型
        
        Returns:
            培训材料
        """
        # 这里可以根据建议类型返回相应的培训材料
        materials_map = {
            "服务态度": {
                "videos": ["服务礼仪培训视频", "沟通技巧视频"],
                "documents": ["服务标准手册", "乘客沟通指南"],
                "practices": ["模拟乘客对话练习", "情绪管理训练"]
            },
            "驾驶技术": {
                "videos": ["安全驾驶技巧", "平稳驾驶方法"],
                "documents": ["驾驶安全手册", "路线规划指南"],
                "practices": ["模拟驾驶练习", "路况应对训练"]
            },
            "车辆状况": {
                "videos": ["车辆清洁标准", "设备维护指南"],
                "documents": ["车辆维护手册", "清洁标准"],
                "practices": ["车辆检查清单", "清洁流程练习"]
            }
        }
        
        return materials_map.get(suggestion_type, {
            "videos": ["通用培训视频"],
            "documents": ["通用培训文档"],
            "practices": ["通用练习"]
        })
    
    def _update_driver_memory(self, driver_id: int, analysis: EvaluationAnalysis, suggestions: List[ImprovementSuggestion]):
        """
        更新司机记忆
        
        Args:
            driver_id: 司机ID
            analysis: 评价分析记录
            suggestions: 改进建议列表
        """
        memory_service = DriverMemoryService(driver_id)
        
        # 存储评价历史
        memory_service.store_memory(
            'rating_history',
            f'rating_{analysis.order_rating.id}',
            {
                'rating': analysis.order_rating.rating,
                'comment': analysis.order_rating.comment,
                'sentiment_score': analysis.sentiment_score,
                'sentiment_label': analysis.sentiment_label,
                'analysis_time': analysis.analysis_time.isoformat()
            },
            importance_score=1.0
        )
        
        # 存储改进记录
        for suggestion in suggestions:
            memory_service.store_memory(
                'improvement_record',
                f'{suggestion.suggestion_type}_{analysis.id}',
                {
                    'area': suggestion.suggestion_type,
                    'suggestion': suggestion.suggestion_content,
                    'priority': suggestion.priority,
                    'generated_time': suggestion.generated_time.isoformat()
                },
                importance_score=1.0 if suggestion.priority == 1 else 0.7
            )
    
    def batch_analyze_evaluations(self, driver_id: int = None, limit: int = 10) -> Dict[str, Any]:
        """
        批量分析评价
        
        Args:
            driver_id: 司机ID（可选）
            limit: 分析数量限制
        
        Returns:
            批量分析结果
        """
        from order.models import OrderRating
        
        try:
            # 获取未分析的评价
            query = OrderRating.objects.filter(analyses__isnull=True)
            if driver_id:
                query = query.filter(driver_id=driver_id)
            
            # 检查是否有可分析的评价
            total_available = query.count()
            if total_available == 0:
                return {
                    'success': True,
                    'message': '没有找到可分析的评价数据',
                    'total_available': 0,
                    'total_analyzed': 0,
                    'success_count': 0,
                    'results': []
                }
            
            ratings = query.order_by('-rating_time')[:limit]
            
            results = []
            for rating in ratings:
                result = self.analyze_evaluation(rating.id)
                results.append(result)
            
            return {
                'total_analyzed': len(results),
                'success_count': len([r for r in results if r.get('success', False)]),
                'results': results
            }
            
        except Exception as e:
            return {'success': False, 'error': str(e)} 